package com.fenquen.sourceguard.dencrypt;

public class Dencrypt {
    private static boolean LIBRARY_LOADED = false;

    static {
        try {
            // 读取当前os的名字,unix/linux的动态库需要以lib打头
            String osName = System.getProperty("os.name");
            if (osName.toLowerCase().contains("windows")) {
                System.loadLibrary("libsourceguard");
            } else {
                System.loadLibrary("sourceguard");
            }
            LIBRARY_LOADED = true;
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static byte[] decrypt(byte[] byteArr) {
        if (LIBRARY_LOADED && needDecrypt(byteArr)) {
            return decrypt0(byteArr);
        }

        return byteArr;
    }

    private static native byte[] decrypt0(byte[] encryptedBytes);

    public static byte[] encrypt(byte[] originByteArr, boolean bindMachine) {
        if (LIBRARY_LOADED) {
            return encrypt0(originByteArr, bindMachine);
        }

        return originByteArr;
    }

    private static native byte[] encrypt0(byte[] originBytes, boolean bindMachine);

    private static boolean needDecrypt(byte[] byteArr) {
        return byteArr[0] == 0x01 &&
                (byteArr[1] == 0x00 || byteArr[1] == (byte) 0xdd) &&
                byteArr[2] == 0x01 &&
                byteArr[3] == 0x00;
    }

}
